<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/resource/css/bootstrap-table.min.css" type="text/css">

<!-- Latest compiled and minified JavaScript -->
<script src="/resource/js/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="/resource/js/bootstrap-table-zh-CN.min.js"></script>

<div id="toolbar">
  <div class="btn-group ml-3" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-info " onclick="AE()">添加</button>
    <button type="button" class="btn btn-danger " onclick="Del()">删除</button>
  </div>
</div>
<div class="modal fade bd-example-modal-lg" id="AEModal" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="AEModalLongTitle">编辑</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="AEForm">
          <input name="id" id="aeid" type="hidden">
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>标题</label>
                <input name="title" placeholder="标题" type="text" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>分类</label>
                <input name="category" placeholder="分类" type="text" class="form-control">
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>顺序</label>
                <input name="order_id" placeholder="顺序" type="number" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>显示状态</label>
                <div>
                  <div class="custom-control custom-radio ">
                    <input name="show" class="custom-control-input" id="radio1" type="radio" checked="" value="1">
                    <label class="custom-control-label" for="radio1">显示</label>
                  </div>
                  <div class="custom-control custom-radio ">
                    <input name="show" class="custom-control-input" id="radio2" type="radio" value="-1">
                    <label class="custom-control-label" for="radio2">隐藏</label>
                  </div>
                </div>

              </div>
            </div>
            
          </div>

          <div class="position-relative form-group">
            <label>内容</label>
            <textarea name="body" class="form-control" rows="12"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="AEajax()">保存</button>
      </div>
    </div>
  </div>
</div>

<script>
  const $table = $('#table')
  let hasInit = false;
  $(function () {
    initTable()
  })

  //搜索
  function search() {
    $("#table").bootstrapTable('refresh');
  }
  //清除搜索
  function cleanSearch() {
    $("select[data-function='search']").each(function (i, domEle) {
      // 选择第一个选项
      $(this).val($(this).find('option:first').val());
    })
    $("input[data-function='search']").each(function (i, domEle) {
      $(domEle).val("")
    })
    $("#table").bootstrapTable('refresh');
  }

  //AE表单
  function AE(data) {
    $('#AEForm')[0].reset();
    if (data != null) {
      $("#AEModalLongTitle").text("编辑")
      $("#AEForm input[type='hidden'],#AEForm input[type='number'],#AEForm input[type='text'],#AEForm select,#AEForm textarea").each(function (i, v) {

        for (let key in data) {
          if (key == $(v).attr("name")) {
            $(v).val(data[key])
          }
        }
      })

      $("#AEForm input[type='checkbox']").each(function (i, v) {
        for (let key in data) {
          if (key == $(v).attr("name")) {
            if (data[key] == 1) {
              $(v).attr("checked", "true")
            } else {
              $(v).removeAttr("checked")
            }
          }
        }
      })

      //单选默认值
      $("#AEForm input[type='radio']").each(function (i, v) {
        for (let key in data) {
          if (key == $(v).attr("name")) {
            $("#AEForm input:radio[name='"+key+"'][value='" + data[key] + "']").prop("checked", true)
          }
        }
      })

    } else {
      $("#AEModalLongTitle").text("添加")
      $("#aeid").val("")

      
    }
    $('#AEModal').modal('show')
  }

  //ae提交
  function AEajax() {
    let d = {}
    let t = $("#AEForm").serializeArray();
    $.each(t, function () {
      d[this.name] = this.value;
    });

    $.ajax({
      type: "POST",
      url: "/{{.setting.admin_path}}/knowledge/ae",
      data: d,
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "保存成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $('#AEModal').modal('hide')
        $("#table").bootstrapTable('refresh');
      }
    });
  }

  //删除数据
  function Del() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function (v, i) {
      ids.push(v.id)
    })

    $.ajax({
      type: "post",
      url: "/{{.setting.admin_path}}/knowledge/del",
      data: { 'ids': ids },
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "删除成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $("#table").bootstrapTable('refresh');
      }
    });

  }


  //初始化表格
  function initTable() {
    $table.bootstrapTable({
      columns: [
        [
          {

          }, {
            title: '<input type="text"  placeholder="ID" class="form-control" name="id" data-function="search" data-type="eq"  />',
          }, {
            title: '<input type="text"  placeholder="标题" class="form-control" name="title" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="分类" class="form-control" name="category" data-function="search" data-type="like" />',
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="show">
                      <option selected value="0">全部</option>
                      <option value="1">显示</option>
                      <option value="-1">隐藏</option>
                    </select>
                  </div>
          `,
          }, {
          }, {
          }, {
            title: `

                  <div class="input-group">
                    <button type="button" class="btn btn-twitter btn-icon-only" onclick="search()">
                      <span class="btn-inner--icon"><i class="fas fa-search"></i></span>
                    </button>
                    <button type="button" class="btn btn-google-plus btn-icon-only" onclick="cleanSearch()">
                      <span class="btn-inner--icon"><i class="fas fa-trash"></i></span>
                    </button>
                  </div>
          `,
          },
        ], [
          {
            checkbox: true,
          }, {
            field: 'id',
            title: 'ID',
            width: 80,
          }, {
            field: 'title',
            title: '标题',
          }, {
            field: 'category',
            title: '分类',
          }, {
            field: 'show',
            title: '是否显示',
            formatter: function (value, row, index) {
              if (row.show == 1) {
                return `是`
              }
              return `否`;
            }
          }, {
            field: 'order_id',
            title: '顺序',
          }, {
            field: 'created_at',
            title: '创建时间',
          }, {
            field: 'operate',
            title: '操作',
            width:120,
            events: {
              'click #edit': function (e, value, row, index) {
                AE(row)
              },
            },
            formatter: function (value, row, index) {
              return `
              <div class="btn-group" role="group" aria-label="Basic example">
                <button id="edit" type="button" class="btn btn-twitter btn-icon-only"><span class="btn-inner--icon"><i class="fas fa-edit"></i></span></button>
              </div>`;
            }
          }
        ]
      ], //列
      url: '/{{.setting.admin_path}}/knowledge',
      method: 'post', //请求方法
      dataType: 'json',//数据格式
      toolbar: '#toolbar',
      pagination: false, //是否显示页码
      showRefresh: true,  //显示刷新按钮
      showColumns: true, //是否显示列下拉列表按钮
      showFullscreen: true, //是否显示全屏按钮
      responseHandler: function (res) {  //response数据处理
        return {
          "rows": res.data.data
        };
      },

      //搜索
      queryParams: function (x) {

        $("select[data-function='search']").each(function (i, domEle) {
          x[$(domEle).attr("name")] = domEle.value
        })

        $("input[data-function='search']").each(function (i, domEle) {
          const bindingDomID = $(domEle).attr("data-select-binding")
          if (bindingDomID != undefined) {
            x[$(bindingDomID).attr("name")] = $(bindingDomID).val()
          }
          x[$(domEle).attr("name")] = domEle.value
        })


        return x
      },
      onColumnSwitch:function(field,checked) { //列选择事件
        window.localStorage.setItem('knowledge_hidden_columns', JSON.stringify($("#table").bootstrapTable('getHiddenColumns').map(function (it) {return it.field})))
        
      },
      onPostBody:function(data){//渲染并在 DOM 中可用后触发
        
        if (hasInit == false &&window.localStorage.getItem('knowledge_hidden_columns') != null) {
          JSON.parse(window.localStorage.getItem('knowledge_hidden_columns')).forEach(v => {
            $("#table").bootstrapTable('hideColumn', v);
          });
        }
        if (!hasInit) hasInit = true
      },

    })
  }

  document.addEventListener('keyup', function(event) {
    if (event.keyCode === 13) {
        // 回车键按下后的操作
        search()
    }
  });
</script>